import time
from api import models
from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication
from rest_framework_jwt.utils import jwt_decode_handler

from rest_framework_jwt.settings import api_settings

from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication

def create_token(user):
    jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
    jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
    payload = jwt_payload_handler(user)
    token = jwt_encode_handler(payload)
    return token

class Authentication(BaseAuthentication):
    def authenticate(self, request):
        #获取请求头部的认证信息AUTHORIZATION
        token = request.META.get('HTTP_AUTHORIZATION')
        user_info = jwt_decode_handler(token)
        user_obj = models.Users.objects.get(id=user_info['user_id'])
        if not user_obj:
            raise exceptions.AuthenticationFailed('用户认证失败')
        return (user_obj,token)